package cn.wolfcode.aspect;


import cn.wolfcode.domain.RedLog;
import cn.wolfcode.mapper.RedLogMapper;
import cn.wolfcode.util.JWTUtils;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class RedLogAspect {
    @Autowired
    HttpServletRequest request;
    @Autowired
    RedLogMapper redLogMapper;
    @Around("@annotation(MyLog)")
    public  void around(ProceedingJoinPoint pjp) throws Throwable {
        String token = request.getHeader("token");
        Claims claims = JWTUtils.parserToken(token);
        String username = claims.get("username").toString();
        RedLog redLog = new RedLog();
        redLog.setOperator(username);
        redLog.setCreateTime(new Date());
        redLog.setClassName(pjp.getTarget().getClass().getName());
        redLog.setMethodName(pjp.getSignature().getName());
        redLog.setParameter(Arrays.toString(pjp.getArgs()));
        long start = System.currentTimeMillis();
        Object proceed = pjp.proceed();
        long end = System.currentTimeMillis();
        redLog.setReturnValue(JSON.toJSONString(proceed));
        redLog.setExecutionTime((int) (end-start));
        redLogMapper.insertRedLog(redLog);
    }
}
